using System;
using System.Diagnostics;
using System.Threading;
using Wolfpack.Core.Checks;
using Wolfpack.Core.Interfaces.Entities;
using Wolfpack.Core.Notification;

namespace Wolfpack.Contrib.Checks.NServiceBusPerformanceCounters
{
    public class NServiceBusSLAViolationCounterCheck : ThresholdCheckBase<NServiceBusSLAViolationCounterCheckConfig>
    {
        protected PerformanceCounter _counter;

        private const string CategoryName = "NServiceBus";
        private const string CounterName = "SLA violation countdown";

        /// <summary>
        /// default ctor
        /// </summary>
        public NServiceBusSLAViolationCounterCheck(NServiceBusSLAViolationCounterCheckConfig config)
            : base(config)
        {
        }

        public override void Initialise()
        {
            _counter = string.IsNullOrEmpty(_config.MachineName)
                          ? new PerformanceCounter(CategoryName, CounterName, _config.InstanceName)
                          : new PerformanceCounter(CategoryName, CounterName, _config.InstanceName, _config.MachineName);
        }

        public override void Execute()
        {
            var smallestValue = long.MaxValue;

            for (var sleepCounter = 0; sleepCounter < 20; sleepCounter++)
            {
                var sample = _counter.NextSample();
                if (sample.RawValue < smallestValue)
                {
                    smallestValue = sample.RawValue;
                }

                Thread.Sleep(500);
            }

            Publish(NotificationRequestBuilder.For(_config.NotificationMode, HealthCheckData.For(
                Identity,
                "{0} seconds until {1} violates its SLA", Convert.ToString(smallestValue), _config.InstanceName)
                .ResultCountIs(Convert.ToInt32(smallestValue))
                ).Build());                
        }

        protected override PluginDescriptor BuildIdentity()
        {
            return new PluginDescriptor
              {
                  Description = "Reports the NServiceBus SLA violation counter for " + _config.InstanceName,
                  TypeId = new Guid("03B3A8E7-BE12-4407-AA83-767CDE9B9E84"),
                  Name = _config.FriendlyId
              };
        }
    }
}